package com.ocom.payhandle.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ocom.common.AcpService;
import com.ocom.common.entity.card.EntityXfRecord;
import com.ocom.common.entity.card.EntityXfRecordProcess;
import com.ocom.common.entity.card.EntityXfRecordProcessExxx;
import com.ocom.common.entity.card.EntiyXfDiscountConfig;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.vo.pyhandle.ConsTimeZoneVo;
import com.ocom.common.vo.pyhandle.EntiyXfDiscountConfigRedisVo;
import com.ocom.mysql.aspect.DataSourceAspect;
import com.ocom.payhandle.dao.IDaoXfDiscountConfig;
import com.ocom.payhandle.feign.XfRecordFeign;
import com.ocom.payhandle.fun.ShoppingCartPayDiscountService;
import com.ocom.payhandle.service.XfDiscountConfigServcie;
import com.ocom.payhandle.service.XfUserparamConfigService;
import com.ocom.payhandle.service.XfZoneDateService;
import com.ocom.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Service
public class XfDiscountConfigServcieImpl extends ServiceImpl<IDaoXfDiscountConfig, EntiyXfDiscountConfig> implements XfDiscountConfigServcie {

    @Autowired
    private XfRecordFeign xfRecordFeign;

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private XfUserparamConfigService xfUserparamConfigService;

    @Autowired
    private XfZoneDateService xfZoneDateService;

    @Autowired
    private XfRecordProcessExxxServiceImpl xfRecordProcessExxxService;

    @Autowired
    private IDaoXfDiscountConfig iDaoXfDiscountConfig;

    @Autowired
    private ShoppingCartPayDiscountService shoppingCartPayDiscountService;



    @DataSourceAspect(type = DataSourceEnum.PART_DB,companyId = "companyId")
    @Override
    public Integer selectSiscount(Long companyId, Long pId, Integer accountType, Integer consType, Date consDate, Integer consMeal, Integer realAmount, EntityXfRecordProcess entityXfRecordProcess) {
        return selectSiscountInner( companyId,  pId,  accountType,  consType,  consDate,  consMeal,  realAmount,  entityXfRecordProcess,null);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB,companyId = "companyId")
    public Integer getDiscount(Long companyId, Long pId, Integer accountType, Integer consType, Date consDate, Integer consMeal, Integer realAmount, EntityXfRecordProcess entityXfRecordProcess) {
        try {
            //计算时区
            Integer timeZone= 0;

            EntiyXfDiscountConfigRedisVo entiyXfDiscountConfigRedisVo =new EntiyXfDiscountConfigRedisVo();

            try {
                ConsTimeZoneVo consTimeZoneVo = xfZoneDateService.getTimeZone(companyId,consDate);
                timeZone = consTimeZoneVo.getConsTimeZone();
            }catch (Exception e1){
                log.error("查时区异常【{}】【{}】【{}】",companyId,consDate,e1);
            }
            if (entityXfRecordProcess.getMerchId() == null) {
                entityXfRecordProcess.setMerchId(0l);
            }

            String canKey="";
            String strDiscountName="";
            List<EntiyXfDiscountConfig> list=new ArrayList<>();
            Long timeLong= Long.valueOf(4*60*60);
            canKey="xf_discount_config#comId:"+companyId+"#accTypeId:"+accountType+"#consType:"+consType+"#mealNo:"+consMeal+ "#merchId:"+ entityXfRecordProcess.getMerchId() +"#";

            Object object = redisUtil.hmGet(canKey,timeZone);

            String mealList= "";

            if (object==null){
                QueryWrapper<EntiyXfDiscountConfig> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("com_id",companyId);
                queryWrapper.eq("cons_time_zone",timeZone);
                queryWrapper.eq("cons_type",consType);
                queryWrapper.eq("meal_no",consMeal);
                queryWrapper.eq("acc_type_id",accountType);
                queryWrapper.select("discount_mode","discount_value","cons_times","amount");
                queryWrapper.orderByAsc("cons_times");
                list=iDaoXfDiscountConfig.selectList(queryWrapper);

                if (list == null || list.size() == 0) {
                    QueryWrapper<EntiyXfDiscountConfig> queryWrapper2 = new QueryWrapper<>();
                    queryWrapper2.eq("com_id", companyId);
                    queryWrapper2.eq("cons_time_zone", timeZone);
                    queryWrapper2.eq("cons_type", consType);
                    queryWrapper2.eq("meal_no", 100);
                    queryWrapper2.apply("find_in_set( " + consMeal + ", meal_list )  and meal_list IS NOT NULL ");
                    queryWrapper2.eq("acc_type_id", accountType);
                    queryWrapper2.select("discount_mode", "discount_value", "cons_times", "meal_no", "meal_list","amount");
                    queryWrapper2.orderByAsc("cons_times");
                    list = iDaoXfDiscountConfig.selectList(queryWrapper2);
                    if(list!=null && list.size()>0){
                        mealList= list.get(0).getMealList();
                    }
                }

                entiyXfDiscountConfigRedisVo.setTimestamp(System.currentTimeMillis());
                entiyXfDiscountConfigRedisVo.setList(list);
                redisUtil.hmSet(canKey,timeZone,entiyXfDiscountConfigRedisVo);
                redisUtil.expire(canKey,timeLong);
            }else {
                entiyXfDiscountConfigRedisVo = (EntiyXfDiscountConfigRedisVo) object;
                list= entiyXfDiscountConfigRedisVo.getList();
                if (list != null && list.size() > 0 && list.get(0).getMealNo()!=null && list.get(0).getMealNo().equals("100")) {
                    mealList = list.get(0).getMealList();
                }
            }

            EntityXfRecord entityXfRecord=new EntityXfRecord();
            entityXfRecord.setPId(pId);
            entityXfRecord.setConsType(consType);
            entityXfRecord.setMealNo(String.valueOf(consMeal));
            entityXfRecord.setConsTime(consDate);
            entityXfRecord.setComId(companyId);
            entityXfRecord.setMerchId(entityXfRecordProcess.getMerchId());
            entityXfRecord.setReserved2(mealList);

//            if(bMerch){
//                entityXfRecord.setReserved1("selectMerchTrue");
//            }else{
//                entityXfRecord.setReserved1("selectMerchFalse");
//            }

            //
            int discount=0;
            int discountMode =0;
            long consMoney = entityXfRecordProcess.getConsMoney();

            //是否需要优惠
            boolean bitD=false;
            if (consType==1 && list != null && list.size() > 0) {
                //饭堂消费的先查询餐段
                Result result=xfRecordFeign.times(entityXfRecord);
                if (result.getCode()!=200){
                    return discount;
                }
                JSONObject discountJson=discountS(discount,result,list,bitD,realAmount, entityXfRecordProcess,"按餐段");
                discount=discountJson.getInteger("discount");
                bitD=discountJson.getBoolean("bitD");
                if (discountJson.getString("strDiscountName")!=null){
                    strDiscountName=discountJson.getString("strDiscountName");
                }
                discountMode = discountJson.getIntValue("discountMode");
                consMoney =  discountJson.getLong("resA");
            }

            entityXfRecord.setReserved2("");
            entityXfRecord.setMealNo("600");
            canKey="xf_discount_config#comId:"+companyId+"#accTypeId:"+accountType+"#consType:"+consType+"#mealNo:600#merchId:"+ entityXfRecordProcess.getMerchId() +"#";
            object = redisUtil.hmGet(canKey,timeZone);

            if (object==null){
                QueryWrapper<EntiyXfDiscountConfig> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("com_id",companyId);
                queryWrapper.eq("cons_time_zone",timeZone);
                queryWrapper.eq("cons_type",consType);
                queryWrapper.eq("meal_no",600);
                queryWrapper.eq("acc_type_id",accountType);
                queryWrapper.select("discount_mode","discount_value","cons_times","amount");
                list=iDaoXfDiscountConfig.selectList(queryWrapper);

                entiyXfDiscountConfigRedisVo.setTimestamp(System.currentTimeMillis());
                entiyXfDiscountConfigRedisVo.setList(list);
                redisUtil.hmSet(canKey,timeZone,entiyXfDiscountConfigRedisVo);
                redisUtil.expire(canKey,timeLong);
            }else {
                entiyXfDiscountConfigRedisVo = (EntiyXfDiscountConfigRedisVo) object;
                list= entiyXfDiscountConfigRedisVo.getList();
            }
            JSONObject discountJson1 = null;
            if (list != null && list.size() > 0) {
                //还有继续查询天
                Result resultWu=xfRecordFeign.timesManJian(entityXfRecord);
                if (resultWu.getCode()!=200){
                    return discount;
                }
                discountJson1=discountManJian(discount,resultWu,list,bitD,realAmount, entityXfRecordProcess,"按天满减");
                discount=discountJson1.getInteger("discount");
                bitD=discountJson1.getBoolean("bitD");
                if (discountJson1.getString("strDiscountName")!=null){
                    strDiscountName=discountJson1.getString("strDiscountName");
                }
                discountMode = discountJson1.getIntValue("discountMode");
                consMoney =  discountJson1.getLong("resA");
            }



            entityXfRecord.setReserved2("");
            entityXfRecord.setMealNo(String.valueOf(500));

            canKey="xf_discount_config#comId:"+companyId+"#accTypeId:"+accountType+"#consType:"+consType+"#mealNo:500#merchId:"+ entityXfRecordProcess.getMerchId() +"#";



            object = redisUtil.hmGet(canKey,timeZone);

            if (object==null){
                QueryWrapper<EntiyXfDiscountConfig> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("com_id",companyId);
                queryWrapper.eq("cons_time_zone",timeZone);
                queryWrapper.eq("cons_type",consType);
                queryWrapper.eq("meal_no",entityXfRecord.getMealNo());
                queryWrapper.eq("acc_type_id",accountType);
                queryWrapper.select("discount_mode","discount_value","cons_times","amount");
                list=iDaoXfDiscountConfig.selectList(queryWrapper);

                entiyXfDiscountConfigRedisVo.setTimestamp(System.currentTimeMillis());
                entiyXfDiscountConfigRedisVo.setList(list);
                redisUtil.hmSet(canKey,timeZone,entiyXfDiscountConfigRedisVo);
                redisUtil.expire(canKey,timeLong);
            }else {
                entiyXfDiscountConfigRedisVo = (EntiyXfDiscountConfigRedisVo) object;
                list= entiyXfDiscountConfigRedisVo.getList();
            }
            JSONObject discountJson= null;
            if(list!=null && list.size()>0){
                //还有继续查询天
                Result resultWu=xfRecordFeign.times(entityXfRecord);
                if (resultWu.getCode()!=200){
                    return discount;
                }
                discountJson=discountS(discount,resultWu,list,bitD,realAmount, entityXfRecordProcess,"按天");
                discount=discountJson.getInteger("discount");
                bitD=discountJson.getBoolean("bitD");
                if (discountJson.getString("strDiscountName")!=null){
                    strDiscountName=discountJson.getString("strDiscountName");
                }
                discountMode = discountJson.getIntValue("discountMode");
                consMoney =  discountJson.getLong("resA");
            }

            entityXfRecord.setMealNo(String.valueOf(1000));
            canKey="xf_discount_config#comId:"+companyId+"#accTypeId:"+accountType+"#consType:"+consType+"#mealNo:1000#merchId:"+ entityXfRecordProcess.getMerchId() +"#";

            object = redisUtil.hmGet(canKey,timeZone);

            if (object==null){
                QueryWrapper<EntiyXfDiscountConfig> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("com_id",companyId);
                queryWrapper.eq("cons_time_zone",timeZone);
                queryWrapper.eq("cons_type",consType);
                queryWrapper.eq("meal_no",entityXfRecord.getMealNo());
                queryWrapper.eq("acc_type_id",accountType);
                queryWrapper.select("discount_mode","discount_value","cons_times","amount");
                list=iDaoXfDiscountConfig.selectList(queryWrapper);

                entiyXfDiscountConfigRedisVo.setTimestamp(System.currentTimeMillis());
                entiyXfDiscountConfigRedisVo.setList(list);
                redisUtil.hmSet(canKey,timeZone,entiyXfDiscountConfigRedisVo);
                redisUtil.expire(canKey,timeLong);
            }else {
                entiyXfDiscountConfigRedisVo = (EntiyXfDiscountConfigRedisVo) object;
                list= entiyXfDiscountConfigRedisVo.getList();
            }

            if (list != null && list.size() > 0) {
                //还有继续查询月
                Result resultQian = xfRecordFeign.xfUserparam(entityXfRecord);
                if (resultQian.getCode() != 200) {
                    return discount;
                }

                JSONObject qianJson = discountS(discount, resultQian, list, bitD, realAmount, entityXfRecordProcess, "按月");
                discount = qianJson.getInteger("discount");
                if (qianJson.getString("strDiscountName") != null) {
                    strDiscountName = qianJson.getString("strDiscountName");
                }
                discountMode = qianJson.getIntValue("discountMode");
                consMoney =  qianJson.getLong("resA");
                //付款金额小于或者等于优惠，直接discount=realAmount；
//                if (realAmount.compareTo(discount) <= 0) {
//                    entityXfRecordProcess.setReserved1(strDiscountName);
//                    return realAmount;
//                }
            }
            if(discountMode == 31){
                entityXfRecordProcess.setConsMoney(consMoney);
            }
            entityXfRecordProcess.setReserved1(strDiscountName);
            return discount;
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }


    private JSONObject discountS(int discount, Result result, List<EntiyXfDiscountConfig> list, boolean bitD, Integer realAmount, EntityXfRecordProcess entityXfRecordProcess, String strDiscountName){
        JSONObject jsonObject= JSON.parseObject(JSON.toJSONString(result.getData()));
        JSONObject reJson=new JSONObject();
        reJson.put("resA",entityXfRecordProcess.getConsMoney());
        reJson.put("discountMode",0);
        if(list!=null && list.size()>0) {
            for (EntiyXfDiscountConfig entiyXfDiscountConfig : list) {
                int times = jsonObject.getInteger("times");
                int consTimes = entiyXfDiscountConfig.getConsTimes();
                if (times < consTimes) {
                    int discountv = 0;
                    discountv = entiyXfDiscountConfig.getDiscountValue();
                    entityXfRecordProcess.setDiscountWay(entiyXfDiscountConfig.getDiscountMode());
                    //1-按金额优惠
                    if (entiyXfDiscountConfig.getDiscountMode() == 1) {
                        strDiscountName = strDiscountName + "：" + "按金额优惠第" + (times + 1) + "次优惠" + AcpService.stringAmount(String.valueOf(entiyXfDiscountConfig.getDiscountValue())) + "元";
                        reJson.put("strDiscountName", strDiscountName);
                        if (bitD) {
                            if (discount < discountv) {
                                discount = discountv;
                                reJson.put("discountMode", 1);
                            }
                        } else {
                            bitD = true;
                            discount = discountv;
                            reJson.put("discountMode", 1);
                        }
                    }
                    //2-按比例打折
                    if (entiyXfDiscountConfig.getDiscountMode() == 2) {
                        strDiscountName = strDiscountName + "：" + "按比例打折第" + (times + 1) + "次打折" + entiyXfDiscountConfig.getDiscountValue() + "%";
                        reJson.put("strDiscountName", strDiscountName);
                        discountv = entiyXfDiscountConfig.getDiscountValue() * realAmount / 100;
                        if (bitD) {
                            if (discount < discountv) {
                                discount = discountv;
                                reJson.put("discountMode", 2);
                            }
                        } else {
                            bitD = true;
                            discount = discountv;
                            reJson.put("discountMode", 2);
                        }
                    }
                    //11-按金额加收
                    if (entiyXfDiscountConfig.getDiscountMode() == 11) {
                        strDiscountName = strDiscountName + "：" + "按金额加收第" + (times + 1) + "次加收" + AcpService.stringAmount(String.valueOf(entiyXfDiscountConfig.getDiscountValue())) + "元";
                        reJson.put("strDiscountName", strDiscountName);
                        discountv = -entiyXfDiscountConfig.getDiscountValue();
                        if (bitD) {
                            if (discount < discountv) {
                                discount = discountv;
                                reJson.put("discountMode", 11);
                            }
                        } else {
                            bitD = true;
                            discount = discountv;
                            reJson.put("discountMode", 11);
                        }
                    }
                    //12-按比例加收
                    if (entiyXfDiscountConfig.getDiscountMode() == 12) {
                        strDiscountName = strDiscountName + "：" + "按比例加收第" + (times + 1) + "次加收" + entiyXfDiscountConfig.getDiscountValue() + "%";
                        reJson.put("strDiscountName", strDiscountName);
                        discountv = -(entiyXfDiscountConfig.getDiscountValue() * realAmount / 100);
                        if (bitD) {
                            if (discount < discountv) {
                                discount = discountv;
                                reJson.put("discountMode", 12);
                            }
                        } else {
                            bitD = true;
                            discount = discountv;
                            reJson.put("discountMode", 12);
                        }
                    }
                    //31-按金额收费
                    if (entiyXfDiscountConfig.getDiscountMode() == 31) {
                        strDiscountName = strDiscountName + "：" + "按固定金额收费，优惠第" + (times + 1) + "次优惠" + AcpService.stringAmount(String.valueOf(entiyXfDiscountConfig.getDiscountValue())) + "元";
                        reJson.put("strDiscountName", strDiscountName);
                        discountv =  entiyXfDiscountConfig.getDiscountValue()  ;
                        if (bitD) {
                            if (discount < discountv) {
                                discount = discountv;
                                reJson.put("resA",- entiyXfDiscountConfig.getAmount());
                                reJson.put("discountMode", 31);
                            }
                        } else {
                            bitD = true;
                            discount = discountv;
                            reJson.put("resA",- entiyXfDiscountConfig.getAmount().longValue());
                            reJson.put("discountMode", 31);
                        }
//
//                        bitD = true;
//                        discount = discountv;
//                        entityXfRecordProcess.setConsMoney(-entiyXfDiscountConfig.getAmount().longValue());
                    }
                    break;
                }
            }
        }
        reJson.put("discount",discount);
        reJson.put("bitD",bitD);
        return reJson;
    }


    /**
     * 满减
     * @param discount
     * @param result
     * @param list
     * @param bitD
     * @param realAmount
     * @param entityXfRecordProcess
     * @param strDiscountName
     * @return
     */
    private JSONObject discountManJian(int discount, Result result, List<EntiyXfDiscountConfig> list, boolean bitD, Integer realAmount, EntityXfRecordProcess entityXfRecordProcess, String strDiscountName){
        Map<String, Integer> merchPayCountMap = JSON.parseObject(JSON.toJSONString(result.getData()), HashMap.class);
        JSONObject reJson=new JSONObject();
        reJson.put("resA",entityXfRecordProcess.getConsMoney());
        reJson.put("discountMode",0);

        if(list!=null && list.size()>0) {
            for (EntiyXfDiscountConfig entiyXfDiscountConfig : list) {
                //满减金额
                if(realAmount<entiyXfDiscountConfig.getAmount()){
                    continue;
                }
                if (entiyXfDiscountConfig.getDiscountMode() != 1) {
                    continue;
                }
                //已经优惠次数
                int times = 0;
                if(merchPayCountMap.containsKey(entiyXfDiscountConfig.getDiscountValue().toString())){
                    times = merchPayCountMap.get(entiyXfDiscountConfig.getDiscountValue().toString());
                }

                int consTimes = entiyXfDiscountConfig.getConsTimes();
                if (times < consTimes) {
                    int discountv = 0;
                    discountv = entiyXfDiscountConfig.getDiscountValue();
                    entityXfRecordProcess.setDiscountWay(entiyXfDiscountConfig.getDiscountMode());
                    //1-按金额优惠
                    if (entiyXfDiscountConfig.getDiscountMode() == 1) {
                        String pointMoney = AcpService.stringAmount(entiyXfDiscountConfig.getAmount().toString());
                        String strDiscountNames = strDiscountName + "：" + "满" + pointMoney + "元,第" + (times + 1) + "次优惠" + AcpService.stringAmount(String.valueOf(entiyXfDiscountConfig.getDiscountValue())) + "元";
                        reJson.put("strDiscountName", strDiscountNames);
                        if (bitD) {
                            if (discount < discountv) {
                                discount = discountv;
                                reJson.put("discountMode", 1);
                            }
                        } else {
                            bitD = true;
                            discount = discountv;
                            reJson.put("discountMode", 1);
                        }
                    }
                }
            }
        }
        reJson.put("discount",discount);
        reJson.put("bitD",bitD);
        return reJson;
    }


    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB,companyId = "companyId")
    public Integer getDiscountProcess(Long companyId, Long pId, Integer accountType, Integer consType, Date consDate, Integer consMeal, Integer realAmount, EntityXfRecordProcess entityXfRecordProcess,List<EntityXfRecordProcessExxx> processExxxList) {
        try {
            //计算时区
            Integer timeZone= 0;

            EntiyXfDiscountConfigRedisVo entiyXfDiscountConfigRedisVo =new EntiyXfDiscountConfigRedisVo();

            try {
                ConsTimeZoneVo consTimeZoneVo = xfZoneDateService.getTimeZone(companyId,consDate);
                timeZone = consTimeZoneVo.getConsTimeZone();
            }catch (Exception e1){
                log.error("查时区异常【{}】【{}】【{}】",companyId,consDate,e1);
            }
            if (entityXfRecordProcess.getMerchId() == null) {
                entityXfRecordProcess.setMerchId(0l);
            }

            String canKey="";
            String strDiscountName="";
            List<EntiyXfDiscountConfig> list=new ArrayList<>();
            Long timeLong= Long.valueOf(4*60*60);
            canKey="xf_discount_config#comId:"+companyId+"#accTypeId:"+accountType+"#consType:"+consType+"#mealNo:"+consMeal+ "#merchId:"+ entityXfRecordProcess.getMerchId() +"#";

            Object object = redisUtil.hmGet(canKey,timeZone);

            String mealList= "";

            if (object==null){
                QueryWrapper<EntiyXfDiscountConfig> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("com_id",companyId);
                queryWrapper.eq("cons_time_zone",timeZone);
                queryWrapper.eq("cons_type",consType);
                queryWrapper.eq("meal_no",consMeal);
                queryWrapper.eq("acc_type_id",accountType);
                queryWrapper.select("discount_mode","discount_value","cons_times","amount");
                queryWrapper.orderByAsc("cons_times");
                list=iDaoXfDiscountConfig.selectList(queryWrapper);

                if (list == null || list.size() == 0) {
                    QueryWrapper<EntiyXfDiscountConfig> queryWrapper2 = new QueryWrapper<>();
                    queryWrapper2.eq("com_id", companyId);
                    queryWrapper2.eq("cons_time_zone", timeZone);
                    queryWrapper2.eq("cons_type", consType);
                    queryWrapper2.eq("meal_no", 100);
                    queryWrapper2.apply("find_in_set( " + consMeal + ", meal_list )  and meal_list IS NOT NULL ");
                    queryWrapper2.eq("acc_type_id", accountType);
                    queryWrapper2.select("discount_mode", "discount_value", "cons_times", "meal_no", "meal_list","amount");
                    queryWrapper2.orderByAsc("cons_times");
                    list = iDaoXfDiscountConfig.selectList(queryWrapper2);
                    if(list!=null && list.size()>0){
                        mealList= list.get(0).getMealList();
                    }
                }

                entiyXfDiscountConfigRedisVo.setTimestamp(System.currentTimeMillis());
                entiyXfDiscountConfigRedisVo.setList(list);
                redisUtil.hmSet(canKey,timeZone,entiyXfDiscountConfigRedisVo);
                redisUtil.expire(canKey,timeLong);
            }else {
                entiyXfDiscountConfigRedisVo = (EntiyXfDiscountConfigRedisVo) object;
                list= entiyXfDiscountConfigRedisVo.getList();
                if (list != null && list.size() > 0 && list.get(0).getMealNo()!=null && list.get(0).getMealNo().equals("100")) {
                    mealList = list.get(0).getMealList();
                }
            }

            EntityXfRecord entityXfRecord=new EntityXfRecord();
            entityXfRecord.setPId(pId);
            entityXfRecord.setConsType(consType);
            entityXfRecord.setMealNo(String.valueOf(consMeal));
            entityXfRecord.setConsTime(consDate);
            entityXfRecord.setComId(companyId);
            entityXfRecord.setMerchId(entityXfRecordProcess.getMerchId());
            entityXfRecord.setReserved2(mealList);


            int discount=0;
            int discountMode =0;
            long consMoney = entityXfRecordProcess.getConsMoney();

            //是否需要优惠
            boolean bitD=false;
            if (consType==1 && list != null && list.size() > 0) {
                //饭堂消费的先查询餐段  TODO
                Result result = null;
                if(processExxxList==null){
                    result=xfRecordProcessExxxService.times(companyId,entityXfRecord);
                }else{
                    result=shoppingCartPayDiscountService.discountTimes(companyId,entityXfRecord,processExxxList);
                }
                if (result.getCode()!=200){
                    return discount;
                }
                JSONObject discountJson=discountS(discount,result,list,bitD,realAmount, entityXfRecordProcess,"按餐段");
                discount=discountJson.getInteger("discount");
                bitD=discountJson.getBoolean("bitD");
                if (discountJson.getString("strDiscountName")!=null){
                    strDiscountName=discountJson.getString("strDiscountName");
                }
                discountMode = discountJson.getIntValue("discountMode");
                consMoney =  discountJson.getLong("resA");
            }

            entityXfRecord.setReserved2("");
            entityXfRecord.setMealNo("600");
            canKey="xf_discount_config#comId:"+companyId+"#accTypeId:"+accountType+"#consType:"+consType+"#mealNo:600#merchId:"+ entityXfRecordProcess.getMerchId() +"#";
            object = redisUtil.hmGet(canKey,timeZone);

            if (object==null){
                QueryWrapper<EntiyXfDiscountConfig> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("com_id",companyId);
                queryWrapper.eq("cons_time_zone",timeZone);
                queryWrapper.eq("cons_type",consType);
                queryWrapper.eq("meal_no",600);
                queryWrapper.eq("acc_type_id",accountType);
                queryWrapper.select("discount_mode","discount_value","cons_times","amount");
                list=iDaoXfDiscountConfig.selectList(queryWrapper);

                entiyXfDiscountConfigRedisVo.setTimestamp(System.currentTimeMillis());
                entiyXfDiscountConfigRedisVo.setList(list);
                redisUtil.hmSet(canKey,timeZone,entiyXfDiscountConfigRedisVo);
                redisUtil.expire(canKey,timeLong);
            }else {
                entiyXfDiscountConfigRedisVo = (EntiyXfDiscountConfigRedisVo) object;
                list= entiyXfDiscountConfigRedisVo.getList();
            }
            JSONObject discountJson1 = null;
            if (list != null && list.size() > 0) {
                //查询满减  TODO
                Result resultWu= null;
                if(processExxxList==null){
                    resultWu=  xfRecordProcessExxxService.timesManJian(companyId,entityXfRecord);
                }else{
                    resultWu=shoppingCartPayDiscountService.discountTimesManJian(companyId,entityXfRecord,processExxxList);
                }
                if (resultWu.getCode()!=200){
                    return discount;
                }
                discountJson1=discountManJian(discount,resultWu,list,bitD,realAmount, entityXfRecordProcess,"按天满减");
                discount=discountJson1.getInteger("discount");
                bitD=discountJson1.getBoolean("bitD");
                if (discountJson1.getString("strDiscountName")!=null){
                    strDiscountName=discountJson1.getString("strDiscountName");
                }
                discountMode = discountJson1.getIntValue("discountMode");
                consMoney =  discountJson1.getLong("resA");
            }



            entityXfRecord.setReserved2("");
            entityXfRecord.setMealNo(String.valueOf(500));

            canKey="xf_discount_config#comId:"+companyId+"#accTypeId:"+accountType+"#consType:"+consType+"#mealNo:500#merchId:"+ entityXfRecordProcess.getMerchId() +"#";

            object = redisUtil.hmGet(canKey,timeZone);

            if (object==null){
                QueryWrapper<EntiyXfDiscountConfig> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("com_id",companyId);
                queryWrapper.eq("cons_time_zone",timeZone);
                queryWrapper.eq("cons_type",consType);
                queryWrapper.eq("meal_no",entityXfRecord.getMealNo());
                queryWrapper.eq("acc_type_id",accountType);
                queryWrapper.select("discount_mode","discount_value","cons_times","amount");
                list=iDaoXfDiscountConfig.selectList(queryWrapper);

                entiyXfDiscountConfigRedisVo.setTimestamp(System.currentTimeMillis());
                entiyXfDiscountConfigRedisVo.setList(list);
                redisUtil.hmSet(canKey,timeZone,entiyXfDiscountConfigRedisVo);
                redisUtil.expire(canKey,timeLong);
            }else {
                entiyXfDiscountConfigRedisVo = (EntiyXfDiscountConfigRedisVo) object;
                list= entiyXfDiscountConfigRedisVo.getList();
            }
            JSONObject discountJson= null;
            if(list!=null && list.size()>0){
                //还有继续查询天   TODO
                Result resultWu= null;
                if(processExxxList==null){
                    resultWu=  xfRecordProcessExxxService.times(companyId,entityXfRecord);
                }else{
                    resultWu=shoppingCartPayDiscountService.discountTimes(companyId,entityXfRecord,processExxxList);
                }
                if (resultWu.getCode()!=200){
                    return discount;
                }
                discountJson=discountS(discount,resultWu,list,bitD,realAmount, entityXfRecordProcess,"按天");
                discount=discountJson.getInteger("discount");
                bitD=discountJson.getBoolean("bitD");
                if (discountJson.getString("strDiscountName")!=null){
                    strDiscountName=discountJson.getString("strDiscountName");
                }
                discountMode = discountJson.getIntValue("discountMode");
                consMoney =  discountJson.getLong("resA");
            }

            entityXfRecord.setMealNo(String.valueOf(1000));
            canKey="xf_discount_config#comId:"+companyId+"#accTypeId:"+accountType+"#consType:"+consType+"#mealNo:1000#merchId:"+ entityXfRecordProcess.getMerchId() +"#";

            object = redisUtil.hmGet(canKey,timeZone);

            if (object==null){
                QueryWrapper<EntiyXfDiscountConfig> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("com_id",companyId);
                queryWrapper.eq("cons_time_zone",timeZone);
                queryWrapper.eq("cons_type",consType);
                queryWrapper.eq("meal_no",entityXfRecord.getMealNo());
                queryWrapper.eq("acc_type_id",accountType);
                queryWrapper.select("discount_mode","discount_value","cons_times","amount");
                list=iDaoXfDiscountConfig.selectList(queryWrapper);

                entiyXfDiscountConfigRedisVo.setTimestamp(System.currentTimeMillis());
                entiyXfDiscountConfigRedisVo.setList(list);
                redisUtil.hmSet(canKey,timeZone,entiyXfDiscountConfigRedisVo);
                redisUtil.expire(canKey,timeLong);
            }else {
                entiyXfDiscountConfigRedisVo = (EntiyXfDiscountConfigRedisVo) object;
                list= entiyXfDiscountConfigRedisVo.getList();
            }

            if (list != null && list.size() > 0) {
                //还有继续查询月  TODO
                Result resultQian= null;
                if(processExxxList==null){
                    resultQian=  xfRecordProcessExxxService.xfUserparam(companyId,entityXfRecord);
                }else{
                    resultQian=shoppingCartPayDiscountService.discountXfUserparam(companyId,entityXfRecord,processExxxList);
                }
                if (resultQian.getCode() != 200) {
                    return discount;
                }

                JSONObject qianJson = discountS(discount, resultQian, list, bitD, realAmount, entityXfRecordProcess, "按月");
                discount = qianJson.getInteger("discount");
                if (qianJson.getString("strDiscountName") != null) {
                    strDiscountName = qianJson.getString("strDiscountName");
                }
                discountMode = qianJson.getIntValue("discountMode");
                consMoney =  qianJson.getLong("resA");
                //付款金额小于或者等于优惠，直接discount=realAmount；
//                if (realAmount.compareTo(discount) <= 0) {
//                    entityXfRecordProcess.setReserved1(strDiscountName);
//                    return realAmount;
//                }
            }
            if(discountMode == 31){
                entityXfRecordProcess.setConsMoney(consMoney);
            }
            entityXfRecordProcess.setReserved1(strDiscountName);
            return discount;
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    @DataSourceAspect(type = DataSourceEnum.PART_DB,companyId = "companyId")
    public int existDiscount(Long companyId,Integer mealNo, Integer accountType,Integer consType,Integer timeZone){
        QueryWrapper<EntiyXfDiscountConfig> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("com_id",companyId);
        if(timeZone!=null){
            queryWrapper.eq("cons_time_zone",timeZone);
        }
        if(mealNo!=null){
            queryWrapper.eq("meal_no",mealNo);
        }
        queryWrapper.eq("cons_type",consType);
        queryWrapper.eq("acc_type_id",accountType);
        return this.count(queryWrapper);
    }


    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB,companyId = "companyId")
    public Integer selectSiscountInner(Long companyId, Long pId, Integer accountType, Integer consType, Date consDate, Integer consMeal, Integer realAmount, EntityXfRecordProcess entityXfRecordProcess,List<EntityXfRecordProcessExxx> processExxxList) {
        int discount = 0;
        try {
            if(companyId == 693l && pId > 0l && entityXfRecordProcess.getPointId().equals(1015L)){
                //咖啡厅按比例打折20%
//                discount = 20 * realAmount / 100;
//                entityXfRecordProcess.setReserved1("按比例打折20%");
                return 0;
            }
        }catch (Exception e){
            log.error("厦门第一医院异常 RiSpl7R8 【{}】",e);
        }


        discount = this.getDiscountProcess(companyId, pId, accountType, consType, consDate, consMeal, realAmount, entityXfRecordProcess,processExxxList);
        if (0 < discount) {
            Integer discountMax = xfUserparamConfigService.getRestrict(companyId, pId, accountType, consType, consDate, consMeal, discount, entityXfRecordProcess,processExxxList);
            if (discount > discountMax) {
                discount = discountMax;
            }
        }
        int consMoney = entityXfRecordProcess.getConsMoney().intValue();
        int realMoney = consMoney + discount;
        if (realMoney > 0) {
            discount -= realMoney;
        }
        return discount;
    }

    @Override
    public Integer selectSiscountBatch(Long companyId, EntityXfRecordProcess entityXfRecordProcess, List<EntityXfRecordProcessExxx> processExxxList) {
        return selectSiscountInner( companyId,  entityXfRecordProcess.getPId(),  entityXfRecordProcess.getAccTypeId(),  entityXfRecordProcess.getConsType(),
                entityXfRecordProcess.getMealDate(),  Integer.valueOf(entityXfRecordProcess.getMealNo()),  entityXfRecordProcess.getRealMoney().intValue(),  entityXfRecordProcess,processExxxList);
    }


}
